<?php

namespace App\Services\BatchTerminateGoldProducts;

use App\Models\GoldEnd;
use App\Models\GoldRecord;
use App\Models\GoldProduct;
use Illuminate\Database\Eloquent\Collection;

class BatchTerminateGoldProducts
{
	protected Collection $goldProducts;

	public function __construct(Collection $collection)
	{
		$this->goldProducts = $collection;
	}

	protected function canBeTerminated(GoldProduct $goldProduct): bool
	{
        /**
         * @var GoldRecord $lastRecord
         */
		$lastRecord = $goldProduct->lastValidRecord();

		if ($goldProduct->isLocking()) {
			return false;
		} elseif ($goldProduct->isDisabled()) {
			return false;
		} elseif ($lastRecord and !$lastRecord->hasAppliedToResell()) {
			return false;
		} else {
			return true;
		}
	}

	public function terminate()
	{
		if ($this->goldProducts->isEmpty()) return;

		foreach ($this->goldProducts as $goldProduct) {

			if (! $this->canBeTerminated($goldProduct)) continue;

            GoldEnd::create([
                'gold_round_id' => $goldProduct->gold_round_id,
                'gold_product_id' => $goldProduct->id,
            ]);
		}
	}
}
